﻿using LbangCMS.Areas.Admin.Models;
using LbangCMS.EFModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LbangCMS.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        public ActionResult List(int categoryId=0,int pageIndex=1,int pageSize=12)
        {
            int totalPage;
            var products = GetList(categoryId, pageIndex, pageSize, out totalPage);
            ListProductModel model = new ListProductModel();
            model.PageIndex = pageIndex;
            model.TotalPage = totalPage;
            if(totalPage>0)
            {
                model.ProductList = new List<ProductModel>();
                foreach (var item in products)
                {
                    model.ProductList.Add(new ProductModel() {
                        ID = item.ID,
                        CategoryId = item.CategoryId,
                        Description = item.Description,
                        ImageSrc = item.ImageSrc,
                        IsPublish=item.IsPublish,
                        IsRecommend=item.IsRecommend,
                        Name=item.Name
                    });
                }
            }
            if(Request.IsAjaxRequest())
            {
                return PartialView("_ListPartial", model);
            }
            return View(model);
        }
        public ActionResult Edit(int id=0)
        {
            var productCategories = GetCategoryList();
            if (productCategories != null && productCategories.Any())
            {
                var categoryModel = new List<ProductCategoryModel>();
                foreach (var item in productCategories)
                {
                    categoryModel.Add(new ProductCategoryModel { ID = item.ID, Name = item.Name });
                }
                ViewBag.Categories = categoryModel;
            }
            if (id>0)
            {
                var product = GetProduct(id);
                var model = new ProductModel();
                model.ID = product.ID;
                model.Name = product.Name;
                model.CategoryId = product.CategoryId;
                model.IsRecommend = product.IsRecommend;
                model.IsPublish = product.IsPublish;
                model.ImageSrc = product.ImageSrc;
                model.Description = product.Description;
                return View(model);
            }
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(ProductModel model)
        {
            if(model.ID>0)
            {
                UpdateProduct(model.ID, model.CategoryId, model.Name, model.ImageSrc, model.IsRecommend, model.IsPublish, model.Description);
            }
            else
            {
                AddProduct(model.CategoryId, model.Name, model.ImageSrc, model.IsRecommend, model.IsPublish, model.Description);
            }
            return Json(new { success=true });
        }

        public ActionResult PropertyList(int productId)
        {
            ViewBag.ProductId = productId;
            var model = new List<PropertyModel>();
            var props = GetPropertyList(productId);
            if(props!=null&&props.Any())
            {
                foreach (var item in props)
                {
                    model.Add(new PropertyModel() { ID = item.ID, PropertyName = item.PropertyName, PropertyValue = item.PropertyValue, SortIndex = item.SortIndex });
                }
            }
            if(Request.IsAjaxRequest())
            {
                return PartialView("_PropertyListPartial", model);
            }
            return View(model);
        }

        public ActionResult Remove(int id)
        {
            var props = GetPropertyList(id);
            if (props != null && props.Any())
            {
                foreach (var item in props)
                {
                    RemoveProperty(item.ID);
                }
            }
            RemoveProduct(id);
            return Json(new { success = true });
        }

        public ActionResult RemoveProperty(int id)
        {
            DeleteProperty(id);
            return Json(new { success = true });
        }

        [HttpPost]
        public ActionResult UpdateProperty(int id,string propertyName,string propertyValue,int sortIndex)
        {
            UpdatePropertyItem(id,propertyName,propertyValue,sortIndex);
            return Json(new { success = true });
        }

        public ActionResult AddProperty(int productId, string propertyName, string propertyValue, int sortIndex)
        {
            AddProductProperty(productId, propertyName, propertyValue, sortIndex);
            return Json(new { success = true });
        }

        #region private method

        public List<ProductCategory> GetCategoryList()
        {
            using (var db = new Database())
            {
                return db.ProductCategories.OrderBy(o => o.SortIndex).ToList();
            }
        }

        

        private List<Product> GetList(int categoryId,int pageIndex,int pageSize,out int totalPage)
        {
            using (var db = new Database())
            {
                if (categoryId > 0)
                {
                    var count = db.Products.Where(o => o.CategoryId == categoryId).Count();
                    totalPage = (int)Math.Ceiling(count / (pageSize * 1M));
                    return db.Products.Where(o => o.CategoryId == categoryId).OrderByDescending(o => o.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    var count = db.Products.Count();
                    totalPage = (int)Math.Ceiling(count / (pageSize * 1M));
                    return db.Products.OrderByDescending(o => o.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }
        }

        private void AddProductProperty(int productId,string propertyName,string propertyValue,int sortIndex)
        {
            using (var db = new Database())
            {
                var prop = new ProductProperty();
                prop.ProductId = productId;
                prop.PropertyName = propertyName;
                prop.PropertyValue = propertyValue;
                prop.SortIndex = sortIndex;
                db.ProductProperties.Add(prop);
                db.SaveChanges();
            }
        }

        private void AddProduct(int categoryId,string name,string imageSrc,bool isRecommend,bool IsPublish,string description)
        {
            using (var db = new Database())
            {
                var product = new Product()
                {
                    CategoryId = categoryId,
                    Name = name,
                    ImageSrc=imageSrc,
                    IsRecommend=isRecommend,
                    IsPublish=IsPublish,
                    Description=description
                };
                db.Products.Add(product);
                db.SaveChanges();
            }
        }

        private void UpdateProduct(int id, int categoryId, string name, string imageSrc, bool isRecommend, bool IsPublish, string description)
        {
            using (var db = new Database())
            {
                var product = db.Products.Where(o => o.ID == id).FirstOrDefault();
                product.CategoryId = categoryId;
                product.Name = name;
                product.ImageSrc = imageSrc;
                product.IsRecommend = isRecommend;
                product.IsPublish = IsPublish;
                product.Description = description;
                db.SaveChanges();
            }
        }

        public void RemoveProduct(int id)
        {
            using (var db = new Database())
            {
                var product = db.Products.Where(o => o.ID == id).FirstOrDefault();
                db.Products.Remove(product);
                db.SaveChanges();
            }
        }

        private void UpdatePropertyItem(int propertyId,string propertyName,string propertyValue,int sortIndex)
        {
            using (var db = new Database())
            {
                var prop = db.ProductProperties.Where(o => o.ID == propertyId).FirstOrDefault();
                if(prop!=null)
                {
                    prop.PropertyName = propertyName;
                    prop.PropertyValue = propertyValue;
                    prop.SortIndex = sortIndex;
                    db.SaveChanges();
                };
               
            }
        }

        private void DeleteProperty(int propertyId)
        {
            using (var db = new Database())
            {
                var prop = db.ProductProperties.Where(o => o.ID == propertyId).FirstOrDefault();
                db.ProductProperties.Remove(prop);
                db.SaveChanges();
            }
        }

        private Product GetProduct(int id)
        {
            using (var db = new Database())
            {
                return db.Products.Where(o => o.ID == id).FirstOrDefault();
            }
        }

        public List<ProductProperty> GetPropertyList(int productId)
        {
            using (var db = new Database())
            {
                return db.ProductProperties.Where(o => o.ProductId == productId).OrderBy(o => o.SortIndex).ToList();
            }
        }
        #endregion
    }
}